import { useState } from "react";
import { Popover, Space, Select, message, Tooltip, Spin, Tag, Typography, Popconfirm } from "antd";
import { find, findIndex } from 'lodash';
import CommonTable from '@/components/CommonTable';
import IconFont from "@/components/IconFont";
import OrderGoodsDetailsContent from "../../../../Actions/common/OrderItemDetailModal/content";
import AddressRender from "./AddressRender";
import SnRender from "./TagRender";
import { CommonText, NumText } from "@/pages/OrderModule/common/components/CommonText";
import { GoodHead, GoodField } from "@/views/components/TableGoods";
import { labelIconMap, labelNameMap } from "@/utils/config";
import { modifyWarehouseOp, updateLabelOP } from "../../../../../services";
import { getUniqueDetail } from '../../../services';
import { cpText } from '@/utils/utils.jsx';
import styles from './index.module.less';

const { Option } = Select;

//地址渲染Icon
const iconStyle = {
	marginLeft: '4px',
	cursor: 'pointer'
}

//订单类型
const orderTypeMap = {
	0: "自发",
	1: "代发",
	2: "直发"
};

//支付状态
const PAY_STATE = {
	0: '未支付',
	1: '已支付',
	3: '部分支付'
};



//订单备注渲染
function OrderRemarkRender(props) {
	const { handleModalOpera, record, columnKey, value } = props;
	return (
		<>
			{value}
			<IconFont type="iconbianji1-copy" style={iconStyle} onClick={() => handleModalOpera(columnKey, record)} />
		</>
	)
}

//快递渲染
function ExpressRender(props) {
	const { handleModalOpera, record, value } = props;
	const bool = value.some(item => item.logisticsCompanyId);
	const showUpdate = [10, 20, 30].includes(record.state) ? <IconFont type="iconbianji1-copy" style={iconStyle} onClick={() => handleModalOpera('setExpress', record)} /> : null;
	if (!bool) {
		return (
			<div>
				<span>未设置快递</span>
				{showUpdate}
			</div>
		);
	}
	return value?.map((v, index) => {
		const company = v.logisticsCompanyName;
		const logisticsNo = v.logisticsNo;
		v.orderSn = record.sn;
		v.deliveryInfoList = record.deliveryInfoList;
		return (
			<Space key={index}>
				<>
					<NumText as="s1" pre={"¥"} num={record.estimateFreightAmount || 0} suffix={company} />
					{showUpdate}
					<CommonText
						as="s1"
						text={logisticsNo}
						extractIcon={
							logisticsNo ? (
								<Typography onClick={() => handleModalOpera('viewLogistics', v)} as="s1" type="primary" style={{ cursor: "pointer", color: '#165DFF' }}>
									查看物流
								</Typography>
							) : null
						}
					/>
					{v.logisticsErrorType != 1 && <CommonText as="s1" text={v.logisticsErrorInfo} />}
				</>
			</Space>
		);
	});
}

//发货仓渲染
function WareHouseRender(props) {
	const { actions, handleSingleUpdate, record, warehouseList, } = props;
    const isExist = findIndex(warehouseList, ['id', record.warehouseId]); //当前选中的仓库是否在下拉中

	//更新发货仓
	const handleUpdateWarehouse = async (warehouseId, index) => {
		const { warehouseName, state: warehouseState, type: warehouseType, uuid: warehouseUuid } = find(warehouseList, ['id', warehouseId]) || {};
		if (warehouseState) {
			return message.info('已禁用的仓库无法选择');
		}
		const { success, msg } = await modifyWarehouseOp({
			warehouseId,
			warehouseName,
			warehouseState,
			warehouseType,
			warehouseUuid,
			ids: [record.id],
			operationPage: actions == 'sysOrder' ? 2 : 3
		})
		if (success) {
			handleSingleUpdate(record.id);
			message.success(msg);
		}
	}

	if ([10, 30].includes(record.state)) {
		return (
			<Select
				placeholder={isExist == -1 && record.warehouseName ? record.warehouseName: '未设定发货仓'}
				value={isExist > -1 ? record.warehouseId: undefined}
				onChange={handleUpdateWarehouse}
				disabled={record.payState}
				style={{ width: "100%" }}
			>
				{warehouseList.map(d => (
					<Option key={d.id} value={d.id} label={d.warehouseName}>
						<Tooltip title={d.warehouseName}>{d.warehouseName}</Tooltip>
					</Option>
				))}
			</Select>
		);
	} else {
		return (
			<span>
				{record.warehouseName}
				{orderTypeMap[record.type] && <span>（{orderTypeMap[record.type]}）</span>}
			</span>
		);
	}
}

//查看唯一码详情
function UniqueDetailTable({ record }) {

	const [loading, setLoading] = useState(false);
	const [tableData, setTableData] = useState([]);
	const getTableData = async () => {
		setLoading(true);
		const { success, data } = await getUniqueDetail({
			orderSn: record["sn"]
		})
		if (success) {
			setTableData(data);
		}
		setLoading(false);
	}

	//未支付展示文字
	if (record.payState == 0) {
		return (
			<span>{PAY_STATE[record['payState']] || ""}</span>
		)
	}
	return (
		<Popover
			arrow
			placement="bottom"
			trigger={['click']}
			onOpenChange={visible => {
				if (visible) {
					getTableData();
				}
			}}
			content={
				<Spin spinning={loading}>
					<CommonTable
						data={tableData}
						columns={[
							{
								width: 180,
								title: "商品编码",
								dataIndex: "sysSkuCode",
								field: "sysSkuCode"
							},
							{
								width: 255.5,
								title: "唯一码",
								dataIndex: "uniqueCode",
								field: "uniqueCode"
							},
							{
								width: 165,
								title: "支付单价",
								dataIndex: "sysGoodsPrice",
								field: "sysGoodsPrice",
								render(v) {
									return <NumText as="s1" type="error" num={v} pre={v ? "¥" : ""} />;
								}
							}
						]}
					/>
				</Spin>
			}
		>
			<span style={{ cursor: 'pointer', color: '#0068FF' }}>{PAY_STATE[record['payState']] || ""}</span>
		</Popover>
	);
}

//渲染商品表头
function GoodsTitleRender({ imageShowConfig, updateImgShowConfig, setImageShowConfig }) {
	const content = (
		<GoodHead initValues={imageShowConfig}
			onChange={v => {
				updateImgShowConfig(v);
				setImageShowConfig(v);
			}}
		/>
	)
	return (
		<>
			<span>商品</span>
			<Popover
				placement="bottom"
				content={content}
			>
				<IconFont style={iconStyle} type="icona-lujing13" />
			</Popover>
		</>
	)
}

//渲染商品信息
function GoodsRender({ value, record, imageShowConfig, handleSingleUpdate, actions}) {
	const [isInit, setIsInit] = useState(0);
	const [id, setId] = useState();
	const TYPE_TEXT_MAP = {
		0: "【包装】",
		1: "【赠品】",
		2: "【跑量包装】"
	};
	const showAll = imageShowConfig.all;
	const accessoryListRenderNum = showAll ? record?.accessoryList?.length : 2 - Math.min(value.length, 2);
	const onClick = val => {
		if (id) {
			setId(null);
		} else {
			setId(val);
		}
	}
	//整个商品的数量
	const goodsLength = Number(value.length) + Number(record.accessoryList.length);
	return (
		<Popover
			zIndex={100}
			overlayStyle={{ maxWidth: "1229px", height: "200px" }}
			content={OrderGoodsDetailsContent({ isInit, handleSingleUpdate, records: record, actions })}
			title="订单商品明细"
			placement="bottom"
			trigger={['click']}
			onOpenChange={visible => {
				if (visible) {
					setIsInit(isInit + 1);
				}
			}}
			getPopupContainer={triggerNode => triggerNode.parentNode || document.body}
		>
			<div style={{ cursor: 'pointer' }} onClick={() => onClick(record.id)}>
				{value?.slice(0, showAll ? value.length : 2)?.map((item, idx) => {
					if (!record.runVolume || item.type === 2) {
						return (
							<GoodField
								key={idx}
								record={{
									image: item['sysGoodsImage'],
									count: item['goodsNum'],
									name: item['sysGoodsName'],
									color: item['sysGoodsSpec'],
									goods: item['sysSkuCode'],
									style: item['sysSpuCode'],
									price: item['goodsPrice'],
									storeId: item.storeId,
                                    refundStatus: item.refundStatus
								}}
                                showRefund={['orderShip', 'sysOrder'].includes(actions) ? true : false}
								config={imageShowConfig}
							/>
						);
					}
				})}
				{record.accessoryList?.slice(0, accessoryListRenderNum)?.map((item, idx) => {
					if (!record.runVolume || item.type === 2) {
						return (
							<GoodField
								key={idx}
								record={{
									image: item['goodsImage'],
									count: item['goodsNum'],
									name: TYPE_TEXT_MAP[item.type] + item['goodsName'],
									color: item['goodsSpec'],
									style: item['spu'],
									goods: item.goodsId,
									price: item['goodsPrice'],
									storeId: item.storeId
								}}
								config={imageShowConfig}
							/>
						);
					}
				})}
				{!showAll && goodsLength > 2 && <div>...</div>}
			</div>
		</Popover>
	);
};



//渲染订单标签
function LableRender(props) {
	const { record, value, handleModalOpera, handleSingleUpdate } = props;

    //删除标签
	const handleDeleteTag = async (item) => {
		const { success, msg } = await updateLabelOP({
			ids: [record.id],
            type: "2",
			labelIds: [item.labelId]
		})
		if (success) {
			handleSingleUpdate(record.id);
			message.success(msg);
		}
	}

	const temLabelNameMap = {
		'red': '红色标',
		'blue': '蓝色标',
		'yellow': '黄色标',
		'purple': '紫色标',
		'black': '黑色标',
	}

	const temLabelIconMap = {
		'red': "iconbiaoqianhon",
		'blue': "iconbiaoqianlan",
		'yellow': "iconbiaoqianhuang",
		'purple': "iconbiaoqianzi",
		'black': "iconbiaoqianhei"
	};

	return (
		<Space size={[0, 4]} direction="horizontal">
			{value.map((item, idx, list) => (
				temLabelNameMap[item.labelName] ? (
					<span className={styles.tagContent} key={idx}>
						<IconFont type={temLabelIconMap[item.labelName]} />
						<Popconfirm
								title="确定删除?"
								onConfirm={() => handleDeleteTag(item)}
								okText="确定"
								cancelText="取消"
							>
								<span className={styles.closeIcon}><IconFont type={"iconguanbi2fill"} /></span>
						</Popconfirm>
					</span>
				) : (
          <span className={styles.tagContent} key={idx}>
						<Tag color="#B1B7C3">
							{item['labelName']}
						</Tag>
						<Popconfirm
							title="确定删除?"
							onConfirm={() => handleDeleteTag(item)}
							okText="确定"
							cancelText="取消"
						>
							<span className={styles.closeIcon}><IconFont type={"iconguanbi2fill"} /></span>
						</Popconfirm>
					</span>
				)
			))}
			<IconFont type="iconbianji1-copy" style={iconStyle} onClick={() => handleModalOpera('setLabel', record)} />
		</Space>
	);
}


//批量复制的title
function RenderBatchCopyTitle(props) {
	const { title, columnKey, selectKeys, orderList } = props;
	return (
		<Space size={4} direction="horizontal">
			<span>{title}</span>
			<IconFont type="iconcopy" style={iconStyle} onClick={() => handleBatchCopy(columnKey, selectKeys, orderList)} />
		</Space>
	);
}

//批量复制功能
const handleBatchCopy = (columnKey, selectKeys, orderList) => {
	if (selectKeys.length == 0) {
		message.info('请勾选订单');
		return;
	}
	const arr = [];
	selectKeys.map((v) => {
		const obj = find(orderList, ['id', v]);
		arr.push(obj);
	});
	if (columnKey == 'sn') {
		const copyText = arr.filter(t => t[columnKey]).map(v => v[columnKey]).join('\r\n');
		cpText(copyText);
	} else {
		const type = columnKey == 'goodsList' ? 'outOrderSn' : 'logisticsNo';
		const list = arr.filter(t => t[columnKey].length > 0);
		const list1 = [];
		for (let i in list) {
			for (let k in list[i][columnKey]) {
				if (list[i][columnKey][k][type]) {
					list1.push(list[i][columnKey][k][type]);
				}
			}
		}
		cpText([...new Set(list1)].join('\r\n'));
	}
}

export const getCellRenderComp = (modalProps) => {
    
	const cellRenderConfig = {
		'deliveryInfoList': {
			'render': (v, r) => (<AddressRender {...{ ...modalProps, record: r }} />)
		},
		'orderRemark': {
			'render': (v, r) => (<OrderRemarkRender {...{ ...modalProps, record: r, value: v, columnKey: 'orderRemark' }} />)
		},
		'sellerMessage': {
			'render': (v, r) => (<OrderRemarkRender {...{ ...modalProps, record: r, value: v, columnKey: 'sellerMessage' }} />)
		},
		'logisticsList': {
			'title': () => (<RenderBatchCopyTitle {...{ ...modalProps, title: '快递', columnKey: 'logisticsList' }} />),
			'render': (v, r) => (<ExpressRender {...{ ...modalProps, record: r, value: v }} />)
		},
		'warehouseName': {
			'render': (v, r) => (<WareHouseRender {...{ ...modalProps, record: r }} />)
		},
		'payState': {
			'render': (v, r) => (<UniqueDetailTable {...{ ...modalProps, record: r }} />)
		},
		'goodsList': {
			'title': () => (<GoodsTitleRender {...modalProps} />),
			'render': (v, r) => (<GoodsRender {...{ ...modalProps, record: r, value: v }} />)
		},
		'labelList': {
			'render': (v, r) => (<LableRender {...{ ...modalProps, record: r, value: v }} />)
		},
		'sn': {
			'title': () => (<RenderBatchCopyTitle {...{ ...modalProps, title: '系统订单号', columnKey: 'sn' }} />),
			'render': (v, r) => (<SnRender {...{ ...modalProps, record: r, value: v }} />)
		},
		'outOrderSn': {
			'title': () => (<RenderBatchCopyTitle {...{ ...modalProps, title: '店铺订单号', columnKey: 'goodsList' }} />),
		},
	}
	return cellRenderConfig;
}

